package com.shushan.setting;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.Constants;
import com.shushan.base.NavigationLoseActivity;
import com.shushan.db.ChildBookDao;
import com.shushan.invitecode.InviteCalendarActivity;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.pages.OpenVipSpendActivity;
import com.shushan.setting.bean.BookBean;
import com.shushan.setting.bean.ChildInfoBean;
import com.shushan.setting.bean.GradeBookBean;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.util.ImageUtils;
import com.shushan.util.Session;
import com.shushan.util.ToolUtils;

import java.util.List;

/**
 * @ClassName: ParentSettingActivity
 * @Desciption: 家长设置界面
 * @author: yichaohua
 * @date: 2018-08-13
 */
public class ParentSettingActivity extends NavigationLoseActivity implements View.OnClickListener {

    private static final String TAG = "ParentSettingActivity";

    private TextView nameText;
    private TextView sexText;
    private TextView gradeText;
    private ImageView chineseImg;
    private ImageView mathImg;
    private ImageView englishImg;
    private ImageView chineseDelImg;
    private ImageView mathDelImg;
    private ImageView englishDelImg;
    private TextView chinesePressTv;
    private TextView mathPressTv;
    private TextView englishPressTv;
    private RelativeLayout nameLayout;
    private RelativeLayout sexLayout;
    private RelativeLayout gradeLayout;
    private RelativeLayout rewardLayout;
    private RelativeLayout passwdLayout;

    private BabyApplication babyApplication = BabyApplication.getInstance();
    private GradeBookBean gradeBookBean;
    private BookBean chineseBook;
    private BookBean mathBook;
    private BookBean englishBook;
    private ChildInfoBean childInfoBean;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.parent_set_activity);

        setTitle("个人资料设置");

        initView();

        getData(true);
    }

    private void initView() {
        nameText = findViewById(R.id.parent_set_name_tv);
        sexText = findViewById(R.id.parent_set_sex_tv);
        gradeText = findViewById(R.id.parent_set_grade_tv);
        chinesePressTv = findViewById(R.id.parent_set_chinese_press_tv);
        mathPressTv = findViewById(R.id.parent_set_math_press_tv);
        englishPressTv = findViewById(R.id.parent_set_english_press_tv);
        chineseImg = findViewById(R.id.parent_set_chinese_img);
        chineseImg.setOnClickListener(this);
        mathImg = findViewById(R.id.parent_set_math_img);
        mathImg.setOnClickListener(this);
        englishImg = findViewById(R.id.parent_set_english_img);
        englishImg.setOnClickListener(this);

        chineseDelImg = findViewById(R.id.parent_set_chinese_del_img);
        chineseDelImg.setOnClickListener(this);
        mathDelImg = findViewById(R.id.parent_set_math_del_img);
        mathDelImg.setOnClickListener(this);
        englishDelImg = findViewById(R.id.parent_set_english_del_img);
        englishDelImg.setOnClickListener(this);
        nameLayout = findViewById(R.id.parent_set_name_layout);
        nameLayout.setOnClickListener(this);
        sexLayout = findViewById(R.id.parent_set_sex_layout);
        sexLayout.setOnClickListener(this);
        gradeLayout = findViewById(R.id.parent_set_grade_layout);
        gradeLayout.setOnClickListener(this);
        rewardLayout = findViewById(R.id.parent_set_reward_setting_layout);
        rewardLayout.setOnClickListener(this);
        passwdLayout = findViewById(R.id.parent_set_passwd_setting_layout);
        passwdLayout.setOnClickListener(this);
    }

    private void getData(final boolean isCreate) {
        showWaitDialog();

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_PARENT_INDEX);
        urlParse.putValue("child_id", babyApplication.getCurrentChildId());

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<ChildInfoBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(ChildInfoBean childInfo) {
                        childInfoBean = childInfo;

                        nameText.setText(childInfoBean.child_name);
                        sexText.setText(childInfoBean.sex==1?"男":"女");
                        String semester = "上";
                        if(!TextUtils.isEmpty(childInfoBean.semester)){
                            semester = childInfoBean.semester.equals("UP")?"上":"下";
                        }
                        gradeText.setText(childInfoBean.grade_name + semester);

                        deleteBook(false,1);
                        deleteBook(false,2);
                        deleteBook(false,3);

                        List<BookBean> bookBeanList = childInfoBean.getBookBeanList();
                        if(!ToolUtils.isListEmpty(bookBeanList)){
                            for (BookBean bookBean : bookBeanList){
                                setBook(bookBean);
                            }
                        }

                        if(isCreate){
                            getGrades(childInfoBean.grade_id,childInfoBean.semester);
                        }

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void setBook(BookBean selectBookBean) {
        if(selectBookBean == null){
            return;
        }

        switch (selectBookBean.subject_id){
            case Constants.SUBJECT_CHINESE_ID:
                chineseDelImg.setVisibility(View.VISIBLE);
                chinesePressTv.setVisibility(View.VISIBLE);
                chinesePressTv.setText(selectBookBean.press_name);
                ImageUtils.loadImageNoBg(this,selectBookBean.cover,chineseImg);
                chineseBook = selectBookBean;
                break;
            case Constants.SUBJECT_MACH_ID:
                mathDelImg.setVisibility(View.VISIBLE);
                mathPressTv.setVisibility(View.VISIBLE);
                mathPressTv.setText(selectBookBean.press_name);
                ImageUtils.loadImageNoBg(this,selectBookBean.cover,mathImg);
                mathBook = selectBookBean;
                break;
            case Constants.SUBJECT_ENGLISH_ID:
                englishDelImg.setVisibility(View.VISIBLE);
                englishPressTv.setVisibility(View.VISIBLE);
                englishPressTv.setText(selectBookBean.press_name);
                ImageUtils.loadImageNoBg(this,selectBookBean.cover,englishImg);
                englishBook = selectBookBean;
                break;
            default:
                break;
        }
    }

    private void postDelete(final int subject) {
        int num = 0;
        if(chineseBook != null){
            num++;
        }

        if(mathBook != null){
            num++;
        }

        if(englishBook != null){
            num++;
        }

        if(num <= 1){
            showToast("只剩一个课本了，不能删除");
            return;
        }

        BookBean bookBean = null;
        if(subject == 1){
            bookBean = chineseBook;
        }else if(subject == 2){
            bookBean = mathBook;
        }else if(subject == 3){
            bookBean = englishBook;
        }

        showWaitDialog();

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.POST_OUTLINE_REMOVE);
        urlParse.putValue("child_id", babyApplication.getCurrentChildId())
                .putValue("outline_id",bookBean.id);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        deleteBook(true,subject);

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });

    }

    private void deleteBook(boolean isHand,int subject) {
        ChildBookDao childBookDao = new ChildBookDao(this);
        switch (subject){
            case 1:
                chineseDelImg.setVisibility(View.GONE);
                chinesePressTv.setVisibility(View.GONE);
                chineseImg.setImageResource(R.drawable.chinese_book_add_bg);
                chineseBook = null;
                if(isHand){
                    childBookDao.deleteSubjectId(Constants.SUBJECT_CHINESE_ID);
                }
                break;
            case 2:
                mathDelImg.setVisibility(View.GONE);
                mathPressTv.setVisibility(View.GONE);
                mathImg.setImageResource(R.drawable.math_book_add_bg);
                mathBook = null;
                if(isHand){
                    childBookDao.deleteSubjectId(Constants.SUBJECT_MACH_ID);
                }
                break;
            case 3:
                englishDelImg.setVisibility(View.GONE);
                englishPressTv.setVisibility(View.GONE);
                englishImg.setImageResource(R.drawable.english_book_add_bg);
                englishBook = null;
                if(isHand){
                    childBookDao.deleteSubjectId(Constants.SUBJECT_ENGLISH_ID);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.parent_set_chinese_img:
                gotoBookSet(1);
                break;
            case R.id.parent_set_math_img:
                gotoBookSet(2);
                break;
            case R.id.parent_set_english_img:
                gotoBookSet(3);
                break;
            case R.id.parent_set_chinese_del_img:
                postDelete(1);
                break;
            case R.id.parent_set_math_del_img:
                postDelete(2);
                break;
            case R.id.parent_set_english_del_img:
                postDelete(3);
                break;
            case R.id.parent_set_name_layout:
                startActivityForResult(ChildNameSetActivity.class);
                break;
            case R.id.parent_set_sex_layout:
                if(childInfoBean == null){
                    showToast("家长设置信息为空");
                    return;
                }
                Intent intent1 = new Intent(this,ChildSexSetActivity.class);
                intent1.putExtra("sex",childInfoBean.sex);
                startActivityForResultAllow(intent1);
                break;
            case R.id.parent_set_grade_layout:
                Intent intent2 = new Intent(this,GradeSettingActivity.class);
                int grade = 1;
                if(childInfoBean != null){
                    int semester = childInfoBean.semester.equals("DOWN")?1:0;
                    grade = ((childInfoBean.grade_id - 1)*2 + 1) + semester;

                    intent2.putExtra("grade",grade);
                }
                startActivityForResultAllow(intent2);
                break;
            case R.id.parent_set_reward_setting_layout:
                startActivity(RewardSettingActivity.class);
                break;
            case R.id.parent_set_passwd_setting_layout:
                Intent intent = new Intent(this,ParentPswSetActivity.class);
                intent.putExtra("isParentSet",true);
                startActivityAllow(intent);
                break;
            default:
                break;
        }
    }

    private void gotoBookSet(int subject) {
        if(childInfoBean == null){
            showToast("家长设置信息为空");
            return;
        }

        Session.getSession().put("chineseBook",chineseBook);
        Session.getSession().put("mathBook",mathBook);
        Session.getSession().put("englishBook",englishBook);

        switch (subject){
            case 1:
                if(gradeBookBean == null || ToolUtils.isListEmpty(gradeBookBean.getChineseBookList())){
                    showToast("该年级无此科目");
                    return;
                }
                Session.getSession().put("bookList",gradeBookBean.getChineseBookList());
                Intent intent1 = new Intent(this,PressSelectActivity.class);
                intent1.putExtra("isParentSet",true);
                intent1.putExtra("gradeId",childInfoBean.grade_id);
                intent1.putExtra("semester",childInfoBean.semester);
                startActivityForResultAllow(intent1);
                break;
            case 2:
                if(gradeBookBean == null || ToolUtils.isListEmpty(gradeBookBean.getMathBookList())){
                    showToast("该年级无此科目");
                    return;
                }
                Session.getSession().put("bookList",gradeBookBean.getMathBookList());
                Intent intent2 = new Intent(this,PressSelectActivity.class);
                intent2.putExtra("isParentSet",true);
                intent2.putExtra("gradeId",childInfoBean.grade_id);
                intent2.putExtra("semester",childInfoBean.semester);
                startActivityForResultAllow(intent2);
                break;
            case 3:
                if(gradeBookBean == null || ToolUtils.isListEmpty(gradeBookBean.getEnglishBookList())){
                    showToast("该年级无此科目");
                    return;
                }
                Session.getSession().put("bookList",gradeBookBean.getEnglishBookList());
                Intent intent3 = new Intent(this,PressSelectActivity.class);
                intent3.putExtra("isParentSet",true);
                intent3.putExtra("gradeId",childInfoBean.grade_id);
                intent3.putExtra("semester",childInfoBean.semester);
                startActivityForResultAllow(intent3);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG,"resultCode=" + resultCode);
        if(resultCode == 100){
            BookBean selectBookBean = (BookBean) Session.getSession().get("selectBookBean");
            setBook(selectBookBean);
        }else if(resultCode == 200){
            String nickname = (String) Session.getSession().get("nickname");
            nameText.setText(nickname);
        }else if(resultCode == 300){
            String sex = data.getStringExtra("sex");
            if(childInfoBean != null){
                if(sex.equals("男")){
                    childInfoBean.sex = 1;
                }else if(sex.equals("女")){
                    childInfoBean.sex = 2;
                }
            }
            sexText.setText(sex);
        }else if(resultCode == 400){
            getData(true);
        }
    }

    private void getGrades(int gradeId, String semester) {
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_GRADE_BOOKS);
        urlParse.putValue("grade_id", gradeId)
                .putValue("semester", semester);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<GradeBookBean>() {

                    @Override
                    protected void onSuccess(GradeBookBean bookBeans) {
                        gradeBookBean = bookBeans;
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        setResult(100);
    }
}
